/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elderberryni2.panels;

import elderberryni2.Main;
import elderberryni2.data.container.DataContainer;
import elderberryni2.interfaces.*;
import info.monitorenter.gui.chart.Chart2D;
import info.monitorenter.gui.chart.IAxis;
import info.monitorenter.gui.chart.IAxisLabelFormatter;
import info.monitorenter.gui.chart.ITrace2D;
import info.monitorenter.gui.chart.axis.AAxis;
import info.monitorenter.gui.chart.axis.AxisLinear;
import info.monitorenter.gui.chart.labelformatters.LabelFormatterNumber;
import info.monitorenter.gui.chart.traces.Trace2DLtd;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JSlider;

/**
 *
 * @author warringer
 */
public class MainChartPanel extends javax.swing.JPanel implements IChartSavable, 
        IDataCollecting {

    /**
     * Creates new form MainChartPanel
     */
    public MainChartPanel(Main parent) {
        this.parent = parent;
        initComponents();
        initChart();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        chartDisplay = new Chart2D();
        jLabel1 = new javax.swing.JLabel();
        intervallLabel = new javax.swing.JLabel();
        intervallSlider = new javax.swing.JSlider();
        jLabel2 = new javax.swing.JLabel();
        saveChartButton = new javax.swing.JButton();
        saveAllButton = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(765, 520));

        javax.swing.GroupLayout chartDisplayLayout = new javax.swing.GroupLayout(chartDisplay);
        chartDisplay.setLayout(chartDisplayLayout);
        chartDisplayLayout.setHorizontalGroup(
            chartDisplayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        chartDisplayLayout.setVerticalGroup(
            chartDisplayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 431, Short.MAX_VALUE)
        );

        jLabel1.setText("Displayed Time Intervall:");

        intervallLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, intervallSlider, org.jdesktop.beansbinding.ELProperty.create("${value}"), intervallLabel, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        intervallSlider.setMajorTickSpacing(50);
        intervallSlider.setMaximum(600);
        intervallSlider.setMinimum(10);
        intervallSlider.setMinorTickSpacing(10);
        intervallSlider.setPaintTicks(true);
        intervallSlider.setSnapToTicks(true);
        intervallSlider.setValue(30);
        intervallSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                intervallSliderStateChanged(evt);
            }
        });

        jLabel2.setText("s");

        saveChartButton.setText("Save Chart");
        saveChartButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveChartButtonActionPerformed(evt);
            }
        });

        saveAllButton.setText("Save All");
        saveAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveAllButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(chartDisplay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(intervallLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2))
                            .addComponent(intervallSlider, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 370, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(saveChartButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(saveAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chartDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(intervallLabel)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(intervallSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saveChartButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveAllButton)))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void saveChartButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveChartButtonActionPerformed
        saveChart();
    }//GEN-LAST:event_saveChartButtonActionPerformed

    private void intervallSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_intervallSliderStateChanged
        JSlider source = (JSlider) evt.getSource();
        if (!source.getValueIsAdjusting()) {
            int size = (int) source.getValue() * 2;    
            changeSize(size);
            duration = size;
        }
    }//GEN-LAST:event_intervallSliderStateChanged

    private void saveAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAllButtonActionPerformed
        parent.saveAllCharts();
    }//GEN-LAST:event_saveAllButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private Chart2D chartDisplay;
    private javax.swing.JLabel intervallLabel;
    private javax.swing.JSlider intervallSlider;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton saveAllButton;
    private javax.swing.JButton saveChartButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    
    private HashMap<String, ITrace2D> traces = null;
    private int savesPerSecond = 2;
    private double lastTime = 0;
    private int duration = 30 * savesPerSecond;
    private IAxis time = null;
    private IAxis alt = null;
    private IAxis temp = null;
    private IAxis vel = null;
    private IAxis acc = null;
    
    private Main parent = null;
    
    private String saveFolder = "";
    
    private void initChart() {
        chartDisplay.getAxisX().setPaintGrid(true);
        chartDisplay.getAxisY().setPaintGrid(true);
        chartDisplay.getAxisX().setAxisTitle(new IAxis.AxisTitle("Mission Time in s"));
        chartDisplay.getAxisY().setAxisTitle(new IAxis.AxisTitle("Altitude in m"));
        time = chartDisplay.getAxisX();
        alt = chartDisplay.getAxisY();
        acc = new AxisLinear();
        acc.setAxisTitle(new IAxis.AxisTitle("Acceleration in m/s²"));
        chartDisplay.addAxisYRight((AAxis) acc);
        vel = new AxisLinear();
        vel.setAxisTitle(new IAxis.AxisTitle("Velocity in m/s"));
        chartDisplay.addAxisYLeft((AAxis) vel);
        
        IAxisLabelFormatter format = new LabelFormatterNumber(new DecimalFormat("###E00"));
        vel.setFormatter(format);
        alt.setFormatter(format);
        
        alt.getAxisTitle().setTitleColor(Color.red);
        vel.getAxisTitle().setTitleColor(Color.blue);
        acc.getAxisTitle().setTitleColor(Color.magenta);
        
        
        
        traces = new HashMap<String, ITrace2D>();
    }

    public void newDataPoint(DataContainer dataPoint) {
        String uuid = dataPoint.getUuid();
        double timestamp = new Double(dataPoint.getTimestamp());
        double difference = Math.abs(lastTime - timestamp);
        if (difference > (1f / savesPerSecond)) {
            lastTime = timestamp;
            ITrace2D traceAlt = null;
            ITrace2D traceVel = null;
            ITrace2D traceAcc = null;
            if (traces.isEmpty() || !traces.containsKey(uuid+"ALT")) {
                traceAlt = new Trace2DLtd(duration, uuid + " Altitude");
                traceAlt.setColor(Color.red);
                traceVel = new Trace2DLtd(duration, uuid + " Velocity");
                traceVel.setColor(Color.blue);
                traceAcc = new Trace2DLtd(duration, uuid + " Acceleration");
                traceAcc.setColor(Color.MAGENTA);
                chartDisplay.addTrace(traceAlt, time, alt);
                chartDisplay.addTrace(traceVel, time, vel);
                chartDisplay.addTrace(traceAcc, time, acc);
                traces.put(uuid + "ALT", traceAlt);
                traces.put(uuid + "VEL", traceVel);
                traces.put(uuid + "ACC", traceAcc);
            } else {
                traceAlt = traces.get(uuid+"ALT");
                traceVel = traces.get(uuid+"VEL");
                traceAcc = traces.get(uuid+"ACC");
            }
            traceAlt.addPoint(timestamp, dataPoint.getLocation().getAltitude());
            traceVel.addPoint(timestamp, dataPoint.getVelocity().getVelVector());
            traceAcc.addPoint(timestamp, dataPoint.getAcceleration().getGravVector());
        }
    }
    
    public void changeSize(int size) {
        Iterator<Entry<String, ITrace2D>> iterator = traces.entrySet().iterator();
        while (iterator.hasNext()) {
            Trace2DLtd trace = (Trace2DLtd) iterator.next().getValue();
            trace.setMaxSize(size);
        }
    }

    public void setSavesPerSecond(int savesPerSecond) {
        this.savesPerSecond = savesPerSecond;
    }

    public void setSaveFolder(String saveFolder) {
        this.saveFolder = saveFolder;
    }

    public void saveChart() {
        try {
            BufferedImage img = chartDisplay.snapShot(1024, 768);
            File out = new File(this.saveFolder+"main.png");
            ImageIO.write(img, "png", out);
        } catch (IOException ex) {
            Logger.getLogger(MainChartPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void clear() {
        traces.clear();
    }
}
